<?php

namespace app\home\controller;

// use app\common\controller\Home;
use think\Controller;

class Pay extends Controller
{
    //继承父类
    public function __construct()
    {
        parent::__construct();

        //加载模型
        $this->BusinessModel = model('Business.Business');
        $this->RegionModel = model('Region');
    }

    //充值界面
    public function index()
    {
        //调用方法判断是否有没有登录
        $controller = new \app\common\controller\Home(false);
        $controller->Islogin();

        //判断是否有Post请求过来
        if($this->request->isPost())
        {
            $money = $this->request->param('money', 0, 'trim');
            $money = floatval($money);

            if($money < 1)
            {
                $this->error("充值金额不能小于1元");
                exit;
            }

            // $json = '{"msg":"下单成功","code":"10001","zfbuseridcode":"","orderId":"order-20230626113343-8618","qrcode":"","originalprice":"10","wxcode":"https://codeimg.zhanzhangfu.com/upload/649900cfcc952724.jpeg","weburl":"https://admin.zhanzhangfu.com/","price":"10.00","qqcode":"","name":"余额充值","zfbcode":"https://codeimg.zhanzhangfu.com/upload/64990154a63468018.jpeg","thirduid":"21","paytype":"wx"}';

            // $result = json_decode($json, true);
            // var_dump($result);
            // exit;

            //调用下单接口
            //封装数据
            $request = [
                'price' => $money, //充值金额
                'name' => '余额充值', //商品名称
                'thirduid' => $this->view->login['id'], //贵平台的用户id 最好给
                'paytype' => 'ali',  //wx 代表微信支付 ali 代表支付宝支付
                'other' => 'zzfpage-alipay', //zzfpage-alipay 支付宝  zzfpage-wxpay 微信支付
                'callbackurl' => 'http://www.520team.com/home/pay/callback',
                'reurl' => 'http://www.520team.com/home/pay/notice', //成功支付跳转地址
            ];

            //封装头信息
            $headers = [
                'Payment-Key:' . '1cfb05c26550',
                'Payment-Secret:' . 'dacfe3895e514ea682a850d85548ec5f'
            ];

            //发送请求         
            $ch = curl_init();
            //设置请求的接口地址
            curl_setopt($ch, CURLOPT_URL, 'https://pay.its500.com/order/createOrder');
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
            curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
            curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
            curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
            // POST数据
            curl_setopt($ch, CURLOPT_POST, TRUE);
            // 把post的变量加上
            curl_setopt($ch, CURLOPT_POSTFIELDS, $request);

            //返回结果是json类型
            $output = curl_exec($ch);

            //将json转换为php的数组
            $data = json_decode($output, true);

            //关闭请求
            curl_close($ch);

            //echo("打印“payking”平台返回的数据");
            echo($output);
            exit;
        }

        return $this->view->fetch();
    }

    //支付成功界面
    public function notice()
    {
        return $this->view->fetch();
    }

    //支付成功的回调通知接口
    public function callback()
    {
        //判断是否有post请求过来
        if($this->request->isPost())
        {
            //获取到所有的数据
            $params = $this->request->param();

            //充值的金额
            $price = isset($params['price']) ? $params['price'] : 0;
            $price = floatval($price);

            //第三方用户id 
            $thirduid = isset($params['thirduid']) ? $params['thirduid'] : 0;

            //支付方式
            $paytype = isset($params['paytype']) ? $params['paytype'] : 0;
            $payment = '';

            switch($paytype)
            {
                case 0:
                    $payment = '微信支付';
                    break;
                case 1:
                    $payment = '支付宝支付';
                    break;
                case 6:
                    $payment = 'QQ支付';
                    break;
            }

            //判断充值金额
            if($price <= 0)
            {
                $this->error('充值金额为0');
                exit;
            }

            $business = $this->BusinessModel->find($thirduid);

            if(!$business)
            {
                $this->error('充值用户不存在');
                exit;
            }


            //开始事务
            $BusinessModel = model('Business.Business');
            $RecordModel = model('Business.Record');

            //开启事务
            $BusinessModel->startTrans();
            $RecordModel->startTrans();

            //更新余额
            $money = floatval($business['money']);
            //相加
            $update = bcadd($money, $price);

            //更新用户余额
            $BusinessData = [
                'id' => $business['id'],
                'money' => $update
            ];

            //验证器
            $validate = [
                [
                    'money' => ['number', '>=:0'],
                ],
                [
                    'money.number'      => '余额必须是数字类型',
                    'money.>='      => '余额必须大于等于0元',
                ]
            ];

            //更新用户余额
            $BusinessStatus = $BusinessModel->validate(...$validate)->isUpdate(true)->save($BusinessData);

            if($BusinessStatus === FALSE)
            {
                $this->error('更新用户余额失败');
                exit;
            }

            //插入消费记录表
            $content = "{$payment}充值了 $price 元";
            $RecordData = [
                'total' => $price,
                'content' => $content,
                'busid' => $business['id']
            ];

            $RecordStatus = $RecordModel->validate('common/Business/Record')->save($RecordData);

            if($RecordStatus === FALSE)
            {
                $BusinessModel->rollback();
                $this->error('添加消费记录失败');
                exit;
            }

            if($BusinessStatus === FALSE || $RecordStatus === FALSE)
            {
                $RecordModel->rollback();
                $BusinessModel->rollback();
                $this->error('充值失败');
                exit;
            }else
            {
                //提交事务
                $BusinessModel->commit();
                $RecordModel->commit();
                $this->success('充值成功');
                exit;
            }
        }
    }
}
